# -*- coding: utf-8 -*-
import os,time
import cv2
import numpy as np
from skimage import io

def run(url):  # 封面图片处理

    # 前景提取
    img = cv2.imread(url)
    # os.remove(url)
    height,width = img.shape[:2]

    size = (width,height)
    while size[0] > 1000 or size[1] > 1000:
        size = (int(size[0] / 2), int(size[1] / 2))

    img = cv2.resize(img, size, interpolation=cv2.INTER_AREA) 

    mask = np.zeros(img.shape[:2],np.uint8)
    bgdModel = np.zeros((1,65),np.float64)
    fgdModel = np.zeros((1,65),np.float64)
    rect = (10,10,size[0]-20, size[1]-20)  # 划定区域
    print(rect)
    cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)    # 函数返回值为mask,bgdModel,fgdModel
    mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')   # 0和2做背景
    # mask2 = np.where((mask==0),0,1).astype('uint8')   # 0和2做背景

    img = img*mask2[:,:,np.newaxis] # 使用蒙板来获取前景区域

    img += 255 * (1 - cv2.cvtColor(mask2, cv2.COLOR_GRAY2BGR))  # 将背景颜色换为白色

    size = (int(size[0] * 2), int(size[1] * 2))
    img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)

    # cv2.imshow("mask", img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    path = 'mask/mask' + str(time.time()) + '.png'
    cv2.imwrite(path, img)
    return path


# run('picture/picture_static.png')
# run('picture/cb44fde41af6ae95d818e114772e5ae5f6f598b5.jpg')

